![]() |
PATH![]() |
![]() ![]() |
A recursive subroutine is a subroutine that calls itself. Recursive subroutines are legal in AppleScript. You can use them to perform repetitive actions. For example, this recursive subroutine generates a factorial. (The factorial of a number is the product of all the positive integers from 1 to that number. For example, 4 factorial is equal to 1 * 2 * 3 * 4, or 24.)
on factorial(x)
if x > 0 then
return x * (factorial(x - 1))
else
return 1
end if
end factorial
-- To call factorial:
factorial(10) --result: 3628800
In the example above, the subroutine factorial is called once from the top level of the script, passing the value 10 . The subroutine then calls itself recursively with a value of x - 1 , or 9 . Each time the subroutine calls itself, it makes another recursive call, until the value of x is 0 . When x is equal to 0 , AppleScript skips to the Else clause and finishes executing all the partially executed subroutines, including the original factorial subroutine call.
When you call a recursive subroutine, AppleScript keeps track of the variables and pending statements in the original (partially executed) subroutine until the recursive subroutine has completed. Because each call uses some memory, the maximum number of pending subroutines is limited by the available memory. As a result, a recursive subroutine may generate an error before the recursive calls complete.
In addition, a recursive subroutine may not be the most efficient solution to a problem. For example, the factorial subroutine shown above can be rewritten to use a Repeat loop instead of a recursive call:
on factorial(x)
set returnVal to 1
if x > 1 then
repeat with n from 2 to x
set returnVal to returnVal * n
end repeat
end if
return returnVal
end factorial